<?php


namespace XinYaTable\Forms\Services;


use XinYaTable\Forms\Repositories\FormCustomViewRepository;
use XinYaTable\Forms\Repositories\FormRepository;

class FormCustomViewService extends BaseService {
    private $_formCustomViewRepository;
    
    public function __construct(FormCustomViewRepository $formCustomViewRepository) {
        $this->_formCustomViewRepository = $formCustomViewRepository;
        parent::__construct();
    }
    
    /**
     * @param int $formId
     * @param int $uid
     *
     * @return mixed
     */
    public function userCustomViewByFormId($formTableName, int $uid) {
        //通过table_name获取表单id
        /** @var FormRepository $formRep */
        $formRep = app(FormRepository::class);
        $formId  = $formRep->getFormByTableName($formTableName,true);
        
        $_userCustomView = $this->_formCustomViewRepository->getCustomViewByForm($formId, $uid);
        if ($_userCustomView->isEmpty()) {
            $this->_formCustomViewRepository->createUserCustomView(
                $this->_formCustomViewRepository->getSystemViewByForm($formId)->forget('form_id', 'uid')->toArray(),
                $formId,
                $uid
            );
            $_userCustomView = $this->_formCustomViewRepository->getCustomViewByForm($formId, $uid);
        }
        
        return $_userCustomView;
    }
    
    /**
     * @param array $viewList
     * @param string $tableName
     * @param int   $uid
     *
     * @return mixed
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function updateUserCustomView(array $viewList, $tableName, int $uid) {
        /** @var FormRepository $formRep */
        $formRep = app(FormRepository::class);
        $formId  = $formRep->getFormByTableName($tableName,true);
        
        $viewList = collect($viewList)->filter(function ($value) {
            return !isset($value['type']);
        })->toArray();
        $this->_formCustomViewRepository->updateUserCustomView($viewList, $formId, $uid);
        
        return $this->_formCustomViewRepository->getCustomViewByForm($formId, $uid);
    }
    
    /**
     * @param int $id
     * @param int $width
     * @param int $uid
     *
     * @return mixed
     * @throws \XinYaTable\Forms\Exceptions\FormException
     */
    public function resizeCustomView(int $id, int $width, int $uid) {
        $customView = $this->_formCustomViewRepository->updateCustomView($id, ['width' => $width]);
        
        return $this->_formCustomViewRepository->getCustomViewByForm($customView->form_id, $uid);
    }
    
}